package io.jt808.multiService;

import java.io.Serializable;
import java.util.*;

public class PackageItem implements Serializable {
    private static final long serialVersionUID = -127867482782298348L;

    private String terminalSerialNo;
    private int messageSerialNo;
    private int totalPackages;
    private int totalBytes;
    private long updateTime;
    private int retransmissionTimes;

    private Map<Integer, byte[]> dataMap = new HashMap<>(5);

    public PackageItem() {
        totalBytes = 0;
    }

    public int getMessageSerialNo() {
        return messageSerialNo;
    }

    public void setMessageSerialNo(int messageSerialNo) {
        this.messageSerialNo = messageSerialNo;
    }

    public int getTotalPackages() {
        return totalPackages;
    }

    public void setTotalPackages(int totalPackages) {
        this.totalPackages = totalPackages;
    }

    public boolean isComplete() {
        return totalPackages == dataMap.size();
    }

    public byte[] getCompleteBytes() {
        byte[] result = new byte[totalBytes];
        int offset = 0;
        for (int i = 1; i <= totalPackages; i++) {
            byte[] bytes = dataMap.get(i);
            System.arraycopy(bytes, 0, result, offset, bytes.length);
            offset += bytes.length;
        }
        return result;
    }

    public void addPackage(int index, byte[] data) {
        totalBytes += data.length;
        dataMap.put(index, data);
    }

    public long getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(long updateTime) {
        this.updateTime = updateTime;
    }

    public int getRetransmissionTimes() {
        return retransmissionTimes;
    }

    public void setRetransmissionTimes(int retransmissionTimes) {
        this.retransmissionTimes = retransmissionTimes;
    }

    public void increaseRetransmissionTimes() {
        this.retransmissionTimes++;
    }

    public String getTerminalSerialNo() {
        return terminalSerialNo;
    }

    public void setTerminalSerialNo(String terminalSerialNo) {
        this.terminalSerialNo = terminalSerialNo;
    }

    public List<Integer> getRetransmissionPackIds() {
        Set<Integer> ks = dataMap.keySet();
        List<Integer> kl = new ArrayList<>(ks);
        Collections.sort(kl);
        List<Integer> vl = new ArrayList<>();
        for (int i = 1; i <= totalPackages; i++) {
            if (Collections.binarySearch(kl, i) == -1) {
                vl.add(i);
            }
        }
        return vl;
    }
}